<template>
  <div class="regulatory-page">
    <div class="return" @click="goBack">
      <Icon size="25" color="#000000" name="arrow-left" class="back" />
      <div class="title">
        <p class="text">{{ getOrderStatusLabel(orderMessage.status) }}</p>
      </div>
    </div>
    <div v-if="chosenAddress" class="address-display">
      <p class="first-line">{{ chosenAddress.region }}</p>
      <p class="second-line">{{ chosenAddress.addressLine }}</p>
      <p class="third-line">{{ chosenAddress.name }} {{ chosenAddress.contact }}</p>
    </div>
    <div class="order-display" v-for="(item, index) in order.items" :key="index">
      <div class="top-display">
        <p class="left-text">{{ item.supplierName }} <Icon size="14" color="#808080" name="arrow" /></p>
        <p class="right-text">{{ getOrderStatus(orderMessage.status) }}</p>
      </div>
      <van-card
          :num="item.quantity"
          :price="item.total"
          :desc="item.orderIdString"
          :title="item.product ? item.product.productName : ''"
          :thumb="item.product && item.product.imageUrl ? require('@/' + item.product.imageUrl) : require('@/assets/products/default.png')"
          class="card"
      >
        <template #tags>
          <van-tag plain type="danger">{{ getOrderStatusLabel(orderMessage.status) }}</van-tag>
        </template>
      </van-card>
    </div>
    <div class="common-container">
      <div class="left-section">
        <p>订单创建时间</p>
      </div>
      <div class="arrow">
        {{ orderMessage.createTime }}
      </div>
    </div>
      <div class="button">
      <van-button v-if="orderMessage.status === '0'" round style="height: 30px;border-color: #FA6408;color: #FA6408" @click="payOrder(orderMessage.orderIdString)">去支付</van-button>
      <van-button v-else-if="orderMessage.status === '2'" round style="height: 30px;border-color: #FA6408;color: #FA6408" @click="confirmReceipt(orderMessage.orderIdString)">确认收货</van-button>
      <van-button v-else-if="orderMessage.status === '3'" round style="height: 30px;border-color: #FA6408;color: #FA6408" @click="reviewOrder(orderMessage.orderIdString)">去评价</van-button>
      <van-button v-else-if="orderMessage.status === '4'" round style="height: 30px;border-color: #FA6408;color: #FA6408" @click="afterSales(orderMessage.orderIdString)">服务进度</van-button>
      </div>
  </div>
</template>


<script>
import {Dialog, Icon, Toast} from "vant";
import http from "@/plugins/http";

export default {
  name: "OrderInfoView",
  components: { Icon },
  data() {
    return {
      orderMessage:{},
      order: {
        items: []  // 用于存储多个商品的数组
      },
      chosenAddress:null,
    };
  },
  activated() {
    const savedOrderMessage = localStorage.getItem("orderMessage");

    // 如果路由参数存在并且本地存储为空，将参数保存到本地
    if (this.$route.params.order && !savedOrderMessage) {
      this.orderMessage = this.$route.params.order;
      this.saveOrderMessageLocally();
    }

    // 如果路由参数为空但本地存储有数据，从本地存储加载
    if (!this.$route.params.order && savedOrderMessage) {
      this.loadOrderMessageFromLocal();
    }

    const orderId = this.orderMessage?.orderIdString;
    console.log("orderInfo: " + orderId);

    // 如果订单 ID 不存在，则获取订单
    if (!this.order.orderId && orderId) {
      this.fetchOrders(orderId);
    }

    // 如果没有选择地址，尝试根据订单中的地址 ID 获取地址
    if (!this.chosenAddress && this.orderMessage?.addressId) {
      this.fetchAddressById(this.orderMessage.addressId);
    }
  },
  methods: {
    goBack() {
      localStorage.removeItem("orderMessage");
      this.$router.go(-1);
    },
    fetchOrders(orderId) {
      if (orderId) {
        http.get(`/items/getById/${orderId}`)
            .then(response => {
              if (response.statusCode === '200') {
                // 假设 response.data 直接是商品的数组
                this.order = {
                  items: response.data
                };

                if (Array.isArray(this.order.items)) {
                  this.fetchSupplierNames(); // 确保调用前 items 已初始化
                } else {
                  console.error("订单中没有商品信息");
                }
                localStorage.setItem("order", JSON.stringify(this.order));
              } else {
                console.log("订单出错");
              }
            })
            .catch(error => {
              console.error("获取订单信息出错:", error);
            });
      } else {
        console.log("没有订单");
      }
    },
    saveOrderMessageLocally() {
      localStorage.setItem("orderMessage", JSON.stringify(this.orderMessage));
    },
    loadOrderMessageFromLocal() {
      const savedOrderMessage = localStorage.getItem("orderMessage");
      if (savedOrderMessage) {
        this.orderMessage = JSON.parse(savedOrderMessage);
      }
    },
    fetchSupplierNames() {
      if (Array.isArray(this.order.items) && this.order.items.length > 0) {
        // 遍历 items 数组，逐个请求商家信息
        this.order.items.forEach(item => {
          if (item.productId) {
            http.get(`/product/${item.productId}`)
                .then(response => {
                  const supplierName = response.data.supplier.supplierName;
                  this.$set(item, 'supplierName', supplierName || '未知供应商');
                  localStorage.setItem("order", JSON.stringify(this.order));
                })
                .catch(error => {
                  console.error(`获取商品 ${item.productId} 的商家信息出错:`, error);
                });
          } else {
            console.error(`商品 ${item.productId} 没有有效的 productId`);
          }
        });
      } else {
        console.error("订单中没有商品信息或商品数组为空");
      }
    },
    fetchAddressById(addressId) {
      const storedUser = JSON.parse(sessionStorage.getItem("username"));
      if (storedUser) {
        http.get(`/address/id/${addressId}`)
            .then(response => {
              const address = response.data;
              if (address) {
                this.chosenAddress = {
                  region: `${address.province} ${address.city} ${address.district}`,
                  addressLine: address.addressLine,
                  name: address.name,
                  contact: address.contact,
                  isDefault: address.moRen === 1
                };
                localStorage.setItem("address", JSON.stringify(this.chosenAddress));
              }
            })
            .catch(error => {
              console.error("通过ID获取地址信息出错:", error);
            });
      } else {
        console.error("没有用户登录");
      }
    },
    getOrderStatus(status) {
      switch (status) {
        case '0':
          return '待发货';
        case '1':
          return '待支付';
        case '2':
          return '待收货';
        case '3':
          return '待评价';
        case '4':
          return '售后中';
        case '6':
          return '退单申请'
        default:
          return '未知状态';
      }
    },
    getOrderStatusLabel(status) {
      switch (status) {
        case '0':
          return '待发货';
        case '1':
          return '待支付';
        case '2':
          return '待收货';
        case '3':
          return '待评价';
        case '4':
          return '售后中';
        case '6':
          return '退单申请'
        default:
          return '未知状态';
      }
    },
    remindShipment(orderId) {
      // Add logic to remind shipment
      Toast.success("已通知商家")
      console.log(orderId);
    },
    payOrder(orderId) {
      Dialog.confirm({
        title: '确认支付',
        message: '您确认要支付该订单吗？',
      })
          .then(() => {
            const payload = {
              orderId: orderId, // 注意这里要传递的是 orderId
              status: "1" // 将订单状态更新为已支付
            };
            http.post('/order/updateStatus', payload)
                .then(response => {
                  if (response.statusCode === "200")
                    Toast.success('支付成功');
                  this.fetchOrders();
                })
                .catch(error => {
                  Toast.fail('更新用户信息出错');
                  console.error("更新用户信息出错:", error);
                });
          })
          .catch(() => {
            Toast.success('取消支付');
          });
    },
    confirmReceipt(orderId) {
      const payload = {
        orderId: orderId,// 注意这里要传递的是 orderId
        status: "3" // 将订单状态更新为已支付
      };
      http.post('/order/updateStatus', payload)
          .then(response => {
            if (response.statusCode === "200") {
              Toast.success('已收货')
              this.fetchOrders();
            } else {
              Toast.fail('收货失败');
              console.error("更新订单信息失败:", response.message);
            }
          })
          .catch(error => {
            Toast.fail('更新订单信息出错');
            console.error("更新订单信息出错:", error);
          });

    },
    reviewOrder(orderId) {
      console.log("订单ID是:",orderId);
      this.$router.push({ name: 'GoReviewView', params: { orderId: orderId } });
    },
    afterSales(orderId) {
      // Add logic to check after-sales service
      console.log(orderId);
    }
  }
}
</script>

<style scoped>
.regulatory-page {
  background-color: #F6F7F9;
  height: 100vh;
}

.return {
  background-color: #FAEAEA;
  padding: 15px;
  display: flex;
  justify-content: center;
  align-items: center;
  position: relative;
}

.back {
  position: absolute;
  left: 10px;
  text-decoration: none;
}

.title {
  display: flex;
  align-items: center;
}

.text {
  margin: 0;
  color: #000000;
  font-size: 16px;
}
.order-display {
  background-color: white;
  margin-left: 10px;
  margin-right: 10px;
  margin-top: 10px;
  padding-bottom: 10px;
  border-radius: 10px;
}
.top-display {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-left: 10px;
  padding-right: 10px;
  cursor: pointer;
  padding-top: 15px;
}

.left-text {
  font-weight: bold;
  font-size: 14px;
  display: flex;
  align-items: center;
}

.right-text {
  font-size: 14px;
  display: flex;
  align-items: center;
}

.card {
  background-color: #ffffff;
}

.right-text {
  color: #FA6408;
}
.common-container {
  margin-top: 10px;
  margin-left: 10px;
  margin-right: 10px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  background-color: #ffffff;
  padding: 15px 15px;
  cursor: pointer;
  border-top-left-radius: 10px;
  border-top-right-radius: 10px;
}
.left-section {
  display: flex;
  align-items: center;
}
.arrow {
  display: flex;
  align-items: center;
}
.address-display {
  background-color: #ffffff;
  padding: 10px;
  margin: 10px;
  border-radius: 10px;
  cursor: pointer;
}

.address-display p {
  margin-left: 10px;
  line-height: 1.5;
}

.first-line {
  font-size: 14px;
  padding-bottom: 5px;
}

.second-line {
  font-weight: bold;
  font-size: 17px;
  padding-bottom: 5px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.third-line {
  font-size: 14px;
}
.button
{
  background-color: white;
  margin-left: 10px;
  margin-right: 10px;
  padding-left: 250px;
  padding-bottom: 10px;
  border-bottom-left-radius: 10px;
  border-bottom-right-radius: 10px;
}
</style>
